package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.entity.Page;

import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired(required = false)
    private EmployeeService employeeService;
//登录
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
       R<Employee> result=employeeService.login(employee);

       if (result.getCode()==1){
           session.setAttribute("employee",result.getData().getId());

       }
       return result;

    }
    //退出
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
    //添加新用户
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        //employee包括了登录界面的填写信息
        //1. 获取当前登陆的用户,补全员工的创建者与修改者
        Long empId= (Long) session.getAttribute("employee");
        //传入创建用户的人
        employee.setCreateUser(empId);
        //修改用户的人
        employee.setUpdateUser(empId);

        //把数据交给service
        employeeService.save(employee);
        return R.success("保存成功");

    }
    /**
     * 作用： 员工列表分页
     * @param page  当前页
     * @param pageSize  页面大小
     * @param name  用户名
     * @return
     */
    @GetMapping("/page")
        public R<Page<Employee>> page(Integer page,Integer pageSize,String name  ){

      Page<Employee> pageResult= employeeService.findByPage(page,pageSize,name);
      return R.success(pageResult);

        }

/**
 * 作用： 更新员工信息
 * @param employee  封装所有提交过来的员工信息
 * @param session   会话域对象
 * @return
 */
    @PutMapping
    public R<String> update(HttpSession session,@RequestBody Employee employee){

        //获取当前用户id
        long empId= (long) session.getAttribute("employee");
        //把修改者id传入employee
        employee.setUpdateUser(empId);

        employeeService.update(employee);

        return R.success("修改成功");

    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable long id){
        R<Employee> result=employeeService.findById(id);
        return result;
    }



}
